<template>
  <el-dialog
    class="addedit-entrust-receipt-dialog"
    width="1200px"
    :visible.sync="dialogVisible"
    :title="operType == 'edit' || formData.entrustReceiptId ? '修改委托协议单' : operType == 'add' ? '新增委托协议单' : '查看委托单详情'"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <div class="title">现场检测委托协议书</div>

    <table border="1" cellpadding="0" cellspacing="0">
      <tr>
        <td>委托方/受检方</td>
        <td>
          <OrganizationSelect
            style="width: 100%;"
            ref="clientOrganizationSelect1"
            v-model="formData.delegationOrganizationName"
            placeholder=""
            filterable
            :disabled="operType == 'detail'"
            @change="(value, findRes) => {
              formData.delegationOrganizationId = findRes ? findRes.entrustOrganizationId : ''
              if (formData.equality === 1) {
                formData.entrustOrganizationId = formData.delegationOrganizationId
                formData.entrustOrganizationName = formData.delegationOrganizationName
              }
              formData.address = findRes ? findRes.addressDetails : ''
              formData.contactsName = findRes ? findRes.contactsName : ''
              formData.contactsMobile = findRes ? findRes.contactsMobile : ''
            }"
          ></OrganizationSelect>
        </td>
        <td>受检方</td>
        <td class="left" width="450px">
          同委托方:
          <el-radio-group
            v-model="formData.equality"
            :disabled="operType == 'detail'"
            @change="(value) => {
              if (value === 1) {
                const findRes = $refs['clientOrganizationSelect1'].organizationList.find(item => item.organizationName === formData.delegationOrganizationName)
                formData.entrustOrganizationId = findRes ? findRes.entrustOrganizationId : ''
                formData.entrustOrganizationName = formData.delegationOrganizationName
              }
            }"
          >
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否（请注明）</el-radio>
          </el-radio-group>
          <OrganizationSelect
            style="width: 100%;"
            ref="clientOrganizationSelect2"
            v-model="formData.delegationOrganizationName"
            placeholder=""
            filterable
            :disabled="operType == 'detail'"
            @change="(value, findRes) => {
              formData.delegationOrganizationId = findRes ? findRes.entrustOrganizationId : ''
              if (formData.equality === 1) {
                formData.entrustOrganizationId = formData.delegationOrganizationId
                formData.entrustOrganizationName = formData.delegationOrganizationName
              }
              formData.address = findRes ? findRes.addressDetails : ''
              formData.contactsName = findRes ? findRes.contactsName : ''
              formData.contactsMobile = findRes ? findRes.contactsMobile : ''
            }"
            v-if="formData.equality === 0"
          ></OrganizationSelect>
        </td>
      </tr>
      <tr>
        <td>通讯地址</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.address"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>邮编</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.postcode"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td>联系人</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.contactsName"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>电话或传真</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.contactsMobile"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td>检测状况</td>
        <td>
          <el-radio-group v-model="formData.detectionStatus" :disabled="operType == 'detail'">
            <el-radio :label="1">首测</el-radio>
            <el-radio :label="2">复测</el-radio>
            <el-radio :label="3">补测</el-radio>
          </el-radio-group>
        </td>
        <td>合同编号</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.agreementNumber"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td>检测类别</td>
        <td colspan="3">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-radio-group v-model="formData.inspectionType_QT" :disabled="operType == 'detail'">
              <el-radio label="5">验收检测</el-radio>
              <el-radio label="2">状态检测</el-radio>
              <el-radio label="4">稳定性检测</el-radio>
              <!-- <el-radio label="1">性能检测</el-radio> -->
            </el-radio-group>
            <el-checkbox-group style="margin-left: 35px;" v-model="formData.inspectionType_FH" :disabled="operType == 'detail'">
              <el-checkbox label="3">防护检测</el-checkbox>
            </el-checkbox-group>
          </div>
        </td>
      </tr>
    </table>
    <table border="1" cellpadding="0" cellspacing="0">
      <tr>
        <td>序号</td>
        <td>设备名称</td>
        <td>生产厂家</td>
        <td>规格型号</td>
        <td>设备编号</td>
        <td></td>
      </tr>
      <tr v-for="(row, index) in formData.equipment" :key="index">
        <td>{{ index + 1 }}</td>
        <td>
          <el-autocomplete
            style="width: 100%;"
            v-model="row.equipmentName"
            :fetch-suggestions="equipmentFetchSuggestions"
            placeholder=""
            value-key="equipmentName"
            placement="bottom"
            :popper-append-to-body="false"
            :disabled="operType == 'detail'"
            @select="(data) => {
              row.equipmentId = data.equipmentId
              row.equipmentTypeNumber = data.specificationModel
              row.equipmentNumber = data.equipmentNumber
            }"
          ></el-autocomplete>
        </td>
        <td>
          <el-autocomplete
            style="width: 100%;"
            v-model="row.manufactureName"
            :fetch-suggestions="manufactureFetchSuggestions"
            placeholder=""
            value-key="manufactureName"
            placement="bottom"
            :popper-append-to-body="false"
            :disabled="operType == 'detail'"
            @select="(data) => {
              row.manufactureId = data.manufactureId
            }"
          ></el-autocomplete>
        </td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="row.equipmentTypeNumber"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="row.equipmentNumber"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>
          <span
            style="
              display: inline-block;
              width: 50px;
              padding: 2px 0;
              border: 1px solid #ccc;
              color: #888;
              border-radius: 2px;
              cursor: pointer;
              position: relative;
              z-index: 999;
            "
            @click="handleRemoveEquipmentRow(index)"
          >-</span>
        </td>
      </tr>
      <tr>
        <td colspan="6">
          <span
            style="
              display: inline-block;
              width: 50px;
              padding: 2px 0;
              border: 1px solid #ccc;
              color: #888;
              border-radius: 2px;
              cursor: pointer;
              position: relative;
              z-index: 999;
            "
            @click="handleAddEquipmentRow"
          >+</span>
        </td>
      </tr>
    </table>
    <table border="1" cellpadding="0" cellspacing="0">
      <tr>
        <td>检测依据</td>
        <td colspan="3">
          <el-radio-group v-model="formData.standard" :disabled="operType == 'detail'">
            <el-radio :label="1">标准方法</el-radio>
            <el-radio :label="2">非标方法</el-radio>
          </el-radio-group>
        </td>
      </tr>
      <tr>
        <td>附带资料</td>
        <td colspan="3">
          <el-checkbox-group v-model="formData.appendProfile" :disabled="operType == 'detail'">
            <el-checkbox label="1">放射诊疗许可证副本复印件</el-checkbox>
            <el-checkbox label="2">产品标识、说明书</el-checkbox>
            <el-checkbox label="3">相关资料的安全证明</el-checkbox>
            <el-checkbox label="4">其他</el-checkbox>
          </el-checkbox-group>
        </td>
      </tr>
      <tr>
        <td>委托方要求</td>
        <td>
          <el-radio-group v-model="formData.entrustRequire" :disabled="operType == 'detail'">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">有</el-radio>
          </el-radio-group>
          <el-input
            style="width: 400px; margin-left: 10px;"
            v-model="formData.entrustRequireDetail"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
            v-if="formData.entrustRequire === 1"
          ></el-input>
        </td>
        <td>是否同意分包</td>
        <td>
          <el-radio-group v-model="formData.subcontract" :disabled="operType == 'detail'">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </td>
      </tr>
      <tr>
        <td>收费（元）</td>
        <td>
          <el-input-number
            style="width: 100px; margin-right: 10px;"
            v-model="formData.signAmount"
            placeholder=""
            :controls="false"
            :precision="2"
            :min="0"
            :disabled="operType == 'detail'"
          ></el-input-number>元
        </td>
        <td>报告发送方式</td>
        <td>
          <el-radio-group v-model="formData.mailMethod" :disabled="operType == 'detail'">
            <el-radio :label="1">自取</el-radio>
            <el-radio :label="2">邮寄</el-radio>
          </el-radio-group>
        </td>
      </tr>
      <tr>
        <td>委托方承诺</td>
        <td class="left" colspan="3">对提供的一切资料和检品的真实性负责；积极配合承检方工作，按时缴纳所需费用。</td>
      </tr>
      <tr>
        <td class="left" colspan="4">
          <span>委托方代表（签字）：</span>
          <div class="sign-box" @click="() => { if (operType != 'detail') showSignDialog = true }">
            <img :src="formData.signOssUrl" alt="">
          </div>
          <span style="margin-left: 500px;">日期：</span>
          <el-date-picker
            v-model="formData.signDate"
            type="date"
            placeholder=""
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :disabled="operType == 'detail'"
          ></el-date-picker>
        </td>
      </tr>
    </table>

    <div class="sub-title">以下由检测机构填写：</div>

    <table border="1" cellpadding="0" cellspacing="0">
      <tr>
        <td class="left" colspan="6">
          <span style="text-indent: 2em;">经审核，委托单位委托检测任务予以接收。并承诺：遵守国家法律法规；保质保量按时完成 检测任务；为委托方的所有商业或技术机密保密。</span>
        </td>
      </tr>
      <tr>
        <td>任务受理编号</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.acceptanceNumber"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>合同签署人或样品接收人</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.signatory"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
        <td>联系电话</td>
        <td>
          <el-input
            style="width: 100%;"
            v-model="formData.signatoryMobile"
            placeholder=""
            :clearable="false"
            :disabled="operType == 'detail'"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td>承检方（盖章）</td>
        <td colspan="2">XXXX科技有限公司</td>
        <td>日期</td>
        <td colspan="2">
          <el-date-picker
            style="width: 100%;"
            v-model="formData.signatorySignDate"
            type="date"
            placeholder=""
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :disabled="operType == 'detail'"
          ></el-date-picker>
        </td>
      </tr>
      <tr>
        <td>公司地址/邮编</td>
        <td class="left" colspan="5">
          宁夏银川市金凤区丰登镇阅海湾中央商务区大连路林带北侧力德财富大厦第 23 层 2303 号  邮编 750016
        </td>
      </tr>
    </table>

    <div class="tip">注：1.本协议书一式两份，双方各执一份，签字后生效。本协议未尽事宜，双方协商解决。</div>

    <div class="dialog-footer" slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <!-- <el-button type="primary" @click="handleSubmit(0)">暂存</el-button> -->
      <el-button style="margin-right: 50px;" type="primary" @click="handleSubmit(1)">保存</el-button>
      <el-button style="margin-right: 50px;" type="primary" :loading="generateBtnLoading" @click="handleGenerate" v-if="formData.entrustReceiptId">生成</el-button>
      <el-button style="margin-right: 50px;" type="primary" @click="handleView" v-if="formData.ossId">查看</el-button>
    </div>

    <Sign
      :show.sync="showSignDialog"
      @sign-success="(data) => {
        formData.signOssId = data.ossId
        formData.signOssUrl = data.url
      }"
    ></Sign>
  </el-dialog>
</template>

<script>
import Sign from '@/components/Sign'
import {
  entrustReceiptDetail,
  entrustReceiptAdd,
  entrustReceiptEdit,
  entrustReceiptGenerator
} from '@/api/entrustReceipt/index.js'
import { entrustEquipmentListAll } from '@/api/person/entrustEquipment'
import { manufactureListing } from '@/api/basicData/manufacture'
import { listByIds } from '@/api/system/oss'

export default {
  name: 'AddEditEntrustReceipt',
  components: {
    Sign
  },
  dicts: [],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    operType: {
      type: String,
      default: 'add',
    },
    row: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      equipmentList: [],
      manufactureList: [],
      formData: {},
      formRules: {
        delegationOrganizationName: [
          { required: true, message: '请输入委托单位', trigger: 'blur' }
        ],
        entrustOrganizationName: [
          { required: true, message: '请输入受检单位', trigger: 'blur' }
        ],
        equality: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入通讯地址', trigger: 'blur' }
        ],
        postcode: [
          { required: true, message: '请输入邮编', trigger: 'blur' }
        ],
        contactsName: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contactsMobile: [
          { required: true, message: '请输入电话或传真', trigger: 'blur' }
        ],
        detectionStatus: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        agreementNumber: [
          { required: true, message: '请输入合同编号', trigger: 'change' }
        ],
        inspectionType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        equipment: [],
        standard: [],
        appendProfile: [],
        entrustRequire: [],
        entrustRequireDetail: [],
        subcontract: [],
        signAmount: [],
        mailMethod: [],
        signOssId: [],
        signDate: [],
        acceptanceNumber: [],
        signatory: [],
        signatoryMobile: [],
        signatorySignDate: []
      },

      showSignDialog: false,

      generateBtnLoading: false,
    }
  },
  watch: {
    'formData.entrustOrganizationId'(newV, oldV) {
      if (!newV) return
      entrustEquipmentListAll({ entrustOrganizationId: newV }).then(res => {
        this.equipmentList = res.data || []
      }).catch(err => {})
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      if (this.operType == 'add' || this.operType == 'edit' || this.operType == 'detail') {
        entrustReceiptDetail(this.row.taskDetectionEquipmentId).then(res => {
          for (let key in this.formData) {
            this.formData[key] = res.data[key]
          }
          this.formData.entrustReceiptId = res.data.entrustReceiptId
          if (!this.formData.delegationOrganizationId) {
            this.formData.delegationOrganizationId = this.row.entrustOrganizationId
          }
          if (!this.formData.entrustOrganizationId) {
            this.formData.entrustOrganizationId = this.row.entrustOrganizationId
          }
          this.formData.inspectionType_QT = this.formData.inspectionType?.replace(/,3|3,/, '') || ''
          this.formData.inspectionType_FH = this.formData.inspectionType?.includes('3') ? ['3'] : []
          this.formData.equipment = this.formData.equipment || []
          if (this.formData.equipment.length <= 0) this.initEquipmentList()
          this.formData.appendProfile = this.formData.appendProfile?.split(',') || []
          if (this.formData.signOssId) {
            listByIds(this.formData.signOssId).then(res => {
              this.formData.signOssUrl = res.data[0].url
            }).catch(err => {})
          }
          console.log('详情数据', JSON.parse(JSON.stringify(this.formData)))
        }).catch(err => {})
      }

      if (this.manufactureList.length <= 0) {
        manufactureListing().then(res => {
          this.manufactureList = res.data || []
        }).catch(err => {})
      }
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        entrustReceiptId: '',
        delegationOrganizationName: '',
        delegationOrganizationId: '',
        entrustOrganizationName: '',
        entrustOrganizationId: '',
        equality: '',
        address: '',
        postcode: '',
        contactsName: '',
        contactsMobile: '',
        detectionStatus: 1,
        agreementNumber: '',
        inspectionType: '',
        inspectionType_QT: '',
        inspectionType_FH: [],
        equipment: [],
        standard: 1,
        appendProfile: [],
        entrustRequire: 0,
        entrustRequireDetail: '',
        subcontract: 0,
        signAmount: '',
        mailMethod: 2,
        signOssId: '',
        signOssUrl: '',
        signDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
        acceptanceNumber: '',
        signatory: '',
        signatoryMobile: '',
        signatorySignDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
        state: '',
        ossId: '',
      }
      this.initEquipmentList()
    },
    // 初始化设备列表
    initEquipmentList() {
      for (let i = 1; i <= 8; i++) {
        this.formData.equipment.push({
          equipmentId: '',
          equipmentName: '',
          equipmentTypeNumber: '',
          equipmentNumber: '',
          manufactureId: '',
          manufactureName: '',
        })
      }
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.taskDetectionEquipmentId = this.row.taskDetectionEquipmentId
      if (data.inspectionType_QT && data.inspectionType_FH.length > 0) {
        data.inspectionType = data.inspectionType_QT + ',' + data.inspectionType_FH.toString()
      }
      if (data.inspectionType_QT && data.inspectionType_FH.length <= 0) {
        data.inspectionType = data.inspectionType_QT
      }
      if (!data.inspectionType_QT && data.inspectionType_FH.length > 0) {
        data.inspectionType = data.inspectionType_FH.toString()
      }
      data.appendProfile = data.appendProfile?.join(',')
      return data
    },
    // 点击暂存/提交
    handleSubmit(state = 0) {
      if (!this.formData.delegationOrganizationName) {
        this.$message.warning('请填写委托方')
        return
      }
      if (!this.formData.entrustOrganizationId) {
        this.$message.warning('请填写受检方')
        return
      }

      let valid = false
      this.formData.equipment.forEach(row => {
        if (valid) return
        if (row.equipmentId) valid = true
      })
      if (!valid) {
        this.$message.warning('请添加设备信息')
        return
      }

      if (!this.formData.signOssId) {
        this.$message.warning('请完成签名')
        return
      }

      const data = this.getFormData()
      data.state = state

      if (!data.inspectionType) {
        this.$message.warning('请填写检测类别')
        return
      }

      let fn = null
      if (this.operType == 'edit' || this.formData.entrustReceiptId) fn = entrustReceiptEdit
      else if (this.operType == 'add') fn = entrustReceiptAdd

      fn(data).then(res => {
        this.$message.success('操作成功')
        entrustReceiptDetail(this.row.taskDetectionEquipmentId).then(res => {
          this.formData.entrustReceiptId = res.data.entrustReceiptId
          this.$forceUpdate()
        })
      }).catch(err => {})
    },
    // 点击生成
    handleGenerate() {
      if (!this.formData.entrustReceiptId) {
        uni.showToast({ title: '请先保存委托协议书数据' })
        return
      }
      this.generateBtnLoading = true
      entrustReceiptGenerator(this.formData.entrustReceiptId).then(res => {
        this.generateBtnLoading = false
        this.$message.success('操作成功')
        entrustReceiptDetail(this.row.taskDetectionEquipmentId).then(res => {
          this.formData.ossId = res.data.ossId
          this.$forceUpdate()
        })
      }).catch(err => {
        this.generateBtnLoading = false
      })
    },
    // 点击查看
    handleView() {
      if (!this.formData.ossId) {
        uni.showToast({ title: '请先生成委托协议书' })
        return
      }
      listByIds(this.formData.ossId).then((res) => {
        window.open(res.data[0]?.url, 'PDF', '')
      }).catch(err => {})
    },
    // 设备名称输入建议数据
    equipmentFetchSuggestions(queryString, callback) {
      const results = this.equipmentList.filter(item => item.equipmentName.indexOf(queryString) > -1)
      callback(results.length > 0 ? results : this.equipmentList)
    },
    // 厂家名称输入建议数据
    manufactureFetchSuggestions(queryString, callback) {
      const results = this.manufactureList.filter(item => item.manufactureName.indexOf(queryString) > -1)
      callback(results.length > 0 ? results : this.manufactureList)
    },
    // 添加设备行
    handleAddEquipmentRow() {
      this.formData.equipment.push({
        equipmentId: '',
        equipmentName: '',
        equipmentTypeNumber: '',
        equipmentNumber: '',
        manufactureId: '',
        manufactureName: '',
      })
    },
    // 删除设备行
    handleRemoveEquipmentRow(index) {
      this.formData.equipment.splice(index, 1)
    }
  },
}
</script>

<style lang="scss" scoped>
.addedit-entrust-receipt-dialog {

  ::v-deep .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }

  .title {
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
  }

  .sub-title {
    margin: 15px 0;
    font-size: 16px;
    font-weight: bold;
    text-indent: 2em;
  }

  .tip {
    margin-top: 5px;
    font-size: 14px;
    text-align: center;
  }

  table {
    width: 100%;
    border-color: #eee;
    text-align: center;
  }

  table tr td {
    padding: 5px 5px;
    height: 40px;
    box-sizing: border-box;
  }

  table tr td.left {
    text-align: left;
  }

  .sign-box {
    display: inline-flex;
    align-items: center;
    padding: 0 10px;
    width: 200px;
    height: 50px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    cursor: pointer;
    vertical-align: middle;
    position: relative;
    z-index: 99;

    img {
      height: 100%;
    }
  }
}
</style>
